import oss2

access_key_id = "***"
access_key_secret = "***"
bucket_name = "***"
endpoint = "***"

def upload_file_to_oss(
        file_path: str,
        object_name_prefix: str="face/",
        access_key_id: str=access_key_id,
        access_key_secret: str=access_key_secret,
        bucket_name: str=bucket_name,
        endpoint: str=endpoint,
        is_secure: bool = False,
        expire_seconds: int = 3600
):
    """
    上传文件到阿里云OSS，并返回访问URL。

    :param access_key_id: 阿里云AccessKey ID
    :param access_key_secret: 阿里云AccessKey Secret
    :param bucket_name: Bucket名称
    :param endpoint: OSS Endpoint（如：oss-cn-hangzhou.aliyuncs.com）
    :param file_path: 本地文件路径
    :param object_name: 上传到OSS后的对象名称（含路径）
    :param is_secure: 是否使用HTTPS，默认True
    :param expire_seconds: 签名URL过期时间（秒），默认1小时
    :return: 文件的访问URL
    """
    fileNames = file_path.replace("\\","/").split("/")
    fileName = fileNames[len(fileNames)-1]
    object_name = object_name_prefix+fileName


    # 初始化Auth对象
    auth = oss2.Auth(access_key_id, access_key_secret)

    # 创建Bucket对象
    bucket = oss2.Bucket(auth, f"{'https://' if is_secure else 'http://'}{endpoint}", bucket_name)

    try:
        # 上传文件
        with open(file_path, 'rb') as fileobj:
            result = bucket.put_object(object_name, fileobj)

        if result.status != 200:
            raise Exception(f"Upload failed with status code {result.status}")

        # 如果是私有读权限，生成带签名的URL
        if bucket.get_object_acl(object_name).acl == oss2.OBJECT_ACL_PRIVATE:
            url = bucket.sign_url('GET', object_name, expire_seconds)
        else:
            # 公共读或公共读写直接拼接URL
            url = f"{'https' if is_secure else 'http'}://{bucket_name}.{endpoint}/{object_name}"

        return url

    except Exception as e:
        raise Exception(f"Error uploading to OSS: {str(e)}")
